// $Id:addressbook.js 18 2009-01-05 02:18:30Z volker.kueffel $


Ext.onReady(function() {

var addressFields=new Array('subdn','givenname','sn','cn', 'mozillanickname', 'mail','mozillasecondemail','nsaImid', 'telephonenumber', 'homephone', 'fax', 'pager','mobile'
							,'mozillahomestreet', 'mozillahomestreet2', 'mozillahomelocalityname', 'mozillahomestate', 'mozillahomepostalcode', 'mozillahomecountryname','street'
							,'mozillaworkstreet2', 'l', 'st', 'postalcode', 'c', 'title', 'department', 'company', 'mozillaworkurl', 'mozillahomeurl', 'mozillacustom1', 'mozillacustom2'
							,'mozillacustom3', 'mozillacustom4', 'description');

var selectedFolder='';
var progressWindow=null;

var prefillCN=false;
				
var resetInputPanel=function () {
	for (i=0; i<addressFields.length; i++) {
		field=inputPanel.findById(addressFields[i]);
		if (field) {
			field.reset();
		}
   	}
	field=inputPanel.findById('folderdn');
	if (field) {
		field.setValue(selectedFolder);
	}
	prefillCN=false;
	panel=inputPanel.findById('tabPanel');
	if (panel) {
		panel.setActiveTab('firstTab');
	}

}
				
var fillCN=function () {
	if (prefillCN) {
		cnField=inputPanel.findById('cn');
		if (cnField) {
			givennameField=inputPanel.findById('givenname');
			newValue='';
			if (givennameField && givennameField.getValue()!='') {
				newValue+=givennameField.getValue().trim();
			}
			snField=inputPanel.findById('sn');
			if (snField && snField.getValue()!='') {
				if (newValue!='') newValue+=' ';
				newValue+=snField.getValue().trim();
			}
			cnField.setValue(newValue);
		}
	}
}

var submitButton=new Ext.Button({
	text     : 'Save',
	disabled : false,
	handler  : function(){
		folderDnField.setValue(selectedFolder);
		progressWindow=Ext.Msg.wait('Storing contact...','Storing data...');
		inputPanel.getForm().submit({url:'store_contact.php'});
	}
});
var subDnField=new Ext.form.Hidden({id:'subdn',name:'subdn'});
var folderDnField=new Ext.form.Hidden({id:'folderdn',name:'folderdn'});
var inputPanel=new Ext.form.FormPanel({
								labelWidth:120,
								border: false,
					            buttons: [submitButton,
					            	{
					                    text     : 'Cancel',
					                    handler  : function(){
					                        editWindow.hide();
					                }
				                }],
				   	        	items: [subDnField,folderDnField,
				   	        	{
		   	        				xtype: 'tabpanel',
		   	        				id: 'tabPanel',
		   	        				deferredRender: false,
		   	        				bodyStyle:'padding:5px 5px 0',
		   	        				activeTab: 0,
		   	        				border: false,
		   	        				items: [{
		   	        					title: 'Contact',
		   	        					id: 'firstTab',
		   	        					items: [
				        	        		{
				        	        			xtype:'fieldset',
				        	        			title: 'Name',
									            autoHeight:true,
           										defaults: {width: 210},
           										defaultType: 'textfield',
				        	        			items: [
				        	        				{
				        	        					id:'givenname',
				        	        					name:'givenname',
				        	        					fieldLabel:'First Name',
				        	        					enableKeyEvents: true,
				        	        					listeners: {
					        	        					'keyup': function(field,newValue,oldValue) {
					        	        						fillCN(inputPanel);
					        	        						}
					        	        				}
				        	        				},	{
				        	        					id:'sn',
				        	        					name:'sn',
				        	        					fieldLabel:'Last Name',
				        	        					enableKeyEvents: true,
				        	        					listeners: {
					        	        					'keyup': function(field,newValue,oldValue) {
					        	        						fillCN(inputPanel);
					        	        					}
				        	        					}
					        	        			},{
				        	        					id:'cn',
				        	        					name:'cn',
				        	        					fieldLabel:'Display Name',
				        	        					enableKeyEvents: true,
				        	        					allowBlank: false,
				        	        					listeners: {
					        	        					'keyup': function(field,newValue,oldValue) {
					        	        						prefillCN=false;
					        	        						}
				        	        					}
				        	        					
				        	        				},
				        	        				{id:'mozillanickname',name:'mozillanickname',fieldLabel:'Nickname'}
				        	        			]
				        	        		},{
				        	        			xtype:'fieldset',
				        	        			title: 'Internet',
									            autoHeight:true,
           										defaults: {width: 210},
           										defaultType: 'textfield',
				        	        			items: [
				        	        				{id:'mail',name:'mail',fieldLabel:'Email', vtype: 'email'},
				        	        				{id:'mozillasecondemail',name:'mozillasecondemail',fieldLabel:'Additional Email', vtype: 'email'},
				        	        				{id:'nsaImid',name:'nsaImid',fieldLabel:'Messenger Name'},
				        	        			]
				        	        		},{
				        	        			xtype:'fieldset',
				        	        			title: 'Phone',
									            autoHeight:true,
           										defaults: {width: 210},
           										defaultType: 'textfield',
				        	        			items: [
				        	        				{id:'telephonenumber',name:'telephonenumber',fieldLabel:'Work Phone'},
				        	        				{id:'homephone',name:'homephone',fieldLabel:'Home Phone'},
				        	        				{id:'fax',name:'fax',fieldLabel:'Fax'},
				        	        				{id:'pager',name:'pager',fieldLabel:'Pager'},
				        	        				{id:'mobile',name:'mobile',fieldLabel:'Mobile'}
				        	        			]
				        	        		}
				        	        	]
				        	        	},{
				   	        				title: 'Address',
				   	        				items:[
				   	        					{
					        	        			xtype:'fieldset',
					        	        			title: 'Private',
										            autoHeight:true,
										            labelWidth:100,
            										defaults: {width: 210},
            										defaultType: 'textfield',
					        	        			items: [
					        	        				{id:'mozillahomestreet',name:'mozillahomestreet',fieldLabel:'Address'},
					        	        				{id:'mozillahomestreet2',name:'mozillahomestreet2',labelSeparator:''},
					        	        				{id:'mozillahomelocalityname',name:'mozillahomelocalityname',fieldLabel:'City'},
					        	        				{id:'mozillahomepostalcode',name:'mozillahomepostalcode',fieldLabel:'Postal Code'},
					        	        				{id:'mozillahomestate',name:'mozillahomestate',fieldLabel:'State'},
					        	        				{id:'mozillahomecountryname',name:'mozillahomecountryname',fieldLabel:'Country'},
					        	        				{id:'mozillahomeurl',name:'mozillahomeurl',fieldLabel:'Website'}
					        	        			]
				        	        			},{
					        	        			xtype:'fieldset',
					        	        			title: 'Business',
										            autoHeight:true,
										            labelWidth:100,
            										defaults: {width: 210},
            										defaultType: 'textfield',
					        	        			items: [
					        	        				{id:'street',name:'street',fieldLabel:'Address'},
					        	        				{id:'mozillaworkstreet2',name:'mozillaworkstreet2',labelSeparator:''},
					        	        				{id:'l',name:'l',fieldLabel:'City'},
					        	        				{id:'postalcode',name:'postalcode',fieldLabel:'Postal Code'},
					        	        				{id:'st',name:'st',fieldLabel:'State'},
					        	        				{id:'c',name:'c',fieldLabel:'Country'},
					        	        				{id:'mozillaworkurl',name:'mozillaworkurl',fieldLabel:'Website'}
					        	        			]
				        	        			}
				   	        				]
				        	        	},{
				        	        		title: 'Misc',
				        	        		autoHeight:true,
				        	        		defaultType:'textfield',
				        	        		layout: 'form',
				        	        		
				        	        		items: [
					        	        		{id:'mozillacustom1',name:'mozillacustom1',fieldLabel:'Miscellaneous 1'},
					        	        		{id:'mozillacustom2',name:'mozillacustom2',fieldLabel:'Miscellaneous 2'},
					        	        		{id:'mozillacustom3',name:'mozillacustom3',fieldLabel:'Miscellaneous 3'},
					        	        		{id:'mozillacustom4',name:'mozillacustom4',fieldLabel:'Miscellaneous 4'},
					        	        		{
					        	        			xtype:'fieldset',
					        	        			title: 'Notes',
					        	        			autoHeight:true,
					        	        			labelWidth: 1,
					        	        			items: [{xtype: 'textarea', id:'description',name:'description',fieldLabel:'', labelSeparator:'',width: 440,height:200}]
				        	        			}
				        	        		]
				        	        	}]
			        	        	}]
					        	    
								});


inputPanel.on({
	actioncomplete: function(form, action){
            if(action.type == 'load'){
            	if (action.success) submitButton.enable();
            } else if(action.type == 'submit'){
            	if (progressWindow) {
            		progressWindow.updateProgress(1);
            		progressWindow.hide();
            	}
            	if (action.success) {
            		editWindow.hide();
            		addressStore.reload();
            	} else {
            		Ext.Msg.alert('Error!',"Contact couldn't be stored");
            	}
            }
    },
	actionfailed: function(form, action){
		if(action.type == 'submit'){
            if (progressWindow) {
            	progressWindow.updateProgress(1);
            	progressWindow.hide();
            }		
			Ext.Msg.alert('Error!',"Contact couldn't be stored");
        }       
    } 
});


var editWindow = new Ext.Window({
	layout      : 'fit',
	hidden:true,
	width       : 500,
	height      : 540,
	closeAction :'hide',
	plain       : true,
	items:  inputPanel,
	modal: true
});


var addressStore=new Ext.data.JsonStore({
        root: 'data',
    	fields: ['sn','givenname','mail','subdn','cn'],
       	url: 'get_contacts.php'
    });
   
   

// user list

 var showAllAction = new Ext.Action({
        text: 'Show All',
        handler: function(){
            addressStore.load({params:{subdn:'',showall:1}});
            userList.setTitle('All Entries');
            addContactButton.disable();
            selectedFolder='';
            folderTree.getSelectionModel().clearSelections();
        },
    });
    
var addContactButton=new Ext.Button({
	text     : 'Add contact',
	disabled : true,
	handler  : function(){
		resetInputPanel();
		prefillCN=true;
		editWindow.show();
		editWindow.setTitle('Add new contact to "'+userList.title+'"');
	}
});

var userList= new Ext.grid.GridPanel({
	store: addressStore,
	region: 'center',
	title: '&nbsp;',
    columns: [
        {header: "Last Name", width: 200, sortable: true, dataIndex: 'sn'},
        {header: "First Name", width: 200, sortable: true, dataIndex: 'givenname'},
        {header: "email", width: 120, sortable: true,  dataIndex: 'mail'},
    ],
    viewConfig: {
        forceFit: true
    },
    tbar:[showAllAction,addContactButton]
});
userList.on("cellclick",function(grid, rowIndex, columnIndex, e) {
    var record = grid.getStore().getAt(rowIndex); 
    if (record) {
    	editWindow.show();
    	submitButton.disable();
    	editWindow.setTitle(record.data.cn);
		resetInputPanel();
    	subDnField.value=record.data.subdn;
    	inputPanel.load({url:'get_contacts.php',params:{subdn:record.data.subdn,full:1,single:1}});
    }
},inputPanel);
        
        
// folder tree

            
var folderLoader=new Ext.tree.TreeLoader({dataUrl:'get_folders.php'});
            
folderLoader.on("beforeload", function(treeLoader, node) {
        this.baseParams.subdn = node.attributes.subdn;
}, folderLoader);

 var addFolderAction = new Ext.Action({
        text: 'New Folder',
        disabled:true,
        handler: function(){
        	parent=folderTree.getSelectionModel().getSelectedNode();
        	if (parent) {
        		if (parent!=root) parent.ensureVisible();
				subNode = parent.appendChild(new Ext.tree.AsyncTreeNode({
                    text:'',
                    leaf:false,
                    allowChildren:true,
                	draggable:false,
	                allowChildren: true,
    	            visible: true,
        	        leaf: false,
        	        id:'newNode'                    
                }));
                subNode.attributes.subdn=parent.attributes.subdn;
                folderEditor.editNode=subNode;
        		folderEditor.startEdit(subNode.ui.textNode);
        	} else {
        		addFolderAction.disable();
        	}
        },
    });


 var root = new Ext.tree.AsyncTreeNode({
	text: 'Address book',
	draggable:false, // disable root node dragging
	id:'root',
	allowChildren: true,
	visible: true,
	leaf: false
});
root.attributes.subdn='';
        
var folderTree=new Ext.tree.TreePanel({
				region: 'west',
				width:200,
				minWidth:75,
				split:true,
				height: 350,
				border: false,
                animate:true, 
                autoScroll:true,
                root: root,
                rootVisible: true,
                loader: folderLoader,
                enableDD:false,
                containerScroll: true,
 				tbar: [addFolderAction]
            });

folderTree.on({
    'click' : function(node) {
		if (node.isExpanded()) {
			addFolderAction.enable();
		} else {
			addFolderAction.disable();
		}
		selectedFolder=node.attributes.subdn;
		addressStore.load({params:{subdn:node.attributes.subdn}});
		userList.setTitle(node.text);
		addContactButton.enable();
	},
    'expandnode' : function(node) {
		selected=folderTree.getSelectionModel().getSelectedNode();
		if(selected && selected==node) {
			addFolderAction.enable();
		}
	},
    scope:folderTree
});


var folderEditor=new Ext.tree.TreeEditor(folderTree,{
    cancelOnEsc: true,
    completeOnEnter: true,
});

folderEditor.on({
    'beforestartedit' : function() {
    	if (this.editNode.id!='newNode') {
    		return false;
    	}
    },
    'canceledit' : function() {
    	if (this.editNode.id=='newNode') {
    		this.editNode.remove();
    	}
    },
    'complete' : function(editor,value) {
    	edited=this.editNode;
    	if (edited.id=='newNode') {
    		name=value.trim();
    		if (name) {
    			subdn='ou='+name;
    			if (edited.attributes.subdn.trim()!='') {
    				subdn+= ','+edited.attributes.subdn;
    			}
    			edited.attributes.subdn=subdn;
    			

    			Ext.Ajax.request({
    				url:'store_folder.php',
    				params: {subdn:edited.attributes.subdn,name:name},
    				callback: createFolderCallback,
    				scope: edited
    			});
    			progressWindow=Ext.Msg.wait('Creating folder "'+name+'"...','Storing data...');
    		} else {
    			edited.remove();
    		}
    	}
    },
    scope:folderEditor
});

function createFolderCallback(options,success,response) {
	if (progressWindow) {
		progressWindow.updateProgress(1);
		progressWindow.hide();
	}
 	data=Ext.util.JSON.decode(response.responseText);
 	if (!data || !data.success) {
 		Ext.Msg.alert('Error!',"Folder couldn't be stored");
 	} 
 	if (data && data.parentId) {
 		parentNode=folderTree.getNodeById(data.parentId);
 		if (parentNode) parentNode.reload();
 	}
}

// Main panel
            
var border = new Ext.Panel({
    title: 'Simple LDAP Address Book',
    layout:'border',
    renderTo:'slabui',
    width:600,
    height: 400,
    items: [
    	folderTree,
    	userList
    ]
});


});
